//
//  TNAddAccountTableViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/14.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNAddAccountTableViewController.h"
#import "TNAddAccountHeadView.h"
#import "Macro.h"
#import "TNAddAccountContentTableViewCell.h"

#define kDestinationsInfos @"destinationsInfos"

@interface TNAddAccountTableViewController () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, TNAddAccountHeadViewDelegate>

@property(nonatomic, strong) TNAddAccountHeadView *headView;

@property(nonatomic, strong) UIPickerView *pick;
@property(nonatomic, strong) NSArray *consumeArr;

@end

@implementation TNAddAccountTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.tableView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    // Do any additional setup after loading the view.
    _headView = [[TNAddAccountHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH / 2 + 50)];
    _headView.delegate = self;
    self.tableView.tableHeaderView = _headView;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _consumeArr = @[@"其它", @"交通", @"餐饮", @"住宿", @"门票", @"购物", @"娱乐"];
    if (!_isNew) {
        self.navigationItem.rightBarButtonItem = nil;
        [self getData];
    } else {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_WIDTH - 40, 20, 40, 40);
        [button setImage:[UIImage imageNamed:@"IconItemSelected"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(keepAndBack) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    }
}

- (void)tapAction
{
    [self.view endEditing:YES];
}

- (void)getData
{
    _headView.tf.text = _model.money;
    for (int i = 0; i < _consumeArr.count; i++) {
        if ([_model.consume isEqualToString:_consumeArr[i]]) {
            _headView.index = i;
            break;
        }
    }
}

- (void)popAction
{
    if (_isNew) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self keepAndBack];
    }
}

- (void)keepAndBack
{
    if ([_headView.tf.text floatValue] > 0) {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        TNAddAccountContentTableViewCell *cell1 = (TNAddAccountContentTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        NSDate *  senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"MM月dd日 HH:mm:ss"];
        [dateformatter setLocale:[NSLocale currentLocale]];
        NSString *  locationString=[dateformatter stringFromDate:senddate];
        NSString *sql = nil;
        if (_isNew) {
            sql = [NSString stringWithFormat:@"INSERT INTO '%@' (money, unit, consume, detailed, time) VALUES ('%@','%@','%@','%@','%@')", _str, _headView.tf.text, cell.textLabel.text, _consumeArr[_headView.index], cell1.tf.text, locationString];
        } else {
            sql = [NSString stringWithFormat:@"UPDATE '%@' SET money = '%@',unit = '%@',consume = '%@',detailed = '%@',time = '%@' WHERE money = '%@' and unit = '%@' and consume = '%@' and detailed = '%@' and time = '%@'", _str, _headView.tf.text, cell.textLabel.text, _consumeArr[_headView.index], cell1.tf.text, locationString, _model.money, _model.unit, _model.consume, _model.detailed, _model.time];
        }
        [_db executeUpdate:sql];
    }
    [self.navigationController popViewControllerAnimated:YES];
    if (_myBlock) {
        _myBlock();
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TNAddAccountHeadViewDelegate

- (void)beginE
{
    _pick.hidden = YES;
}

- (void)endE
{
    [self.view endEditing:YES];
}

- (void)seleteItem
{
    [self beginE];
    [self endE];
}

#pragma mark - tableViewDataSourse

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isNew) {
        return 1;
    } else {
        return 2;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 40;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"flag"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if (_isNew) {
                cell.textLabel.text = _unitArr[0];
            } else {
                cell.textLabel.text = _model.unit;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            TNAddAccountContentTableViewCell *cell = [[TNAddAccountContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"add"];
            if (_model.detailed.length) {
                cell.tf.text = _model.detailed;
            }
            cell.tf.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"flag"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = @"删除消费记录";
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.textColor = [UIColor redColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _pick.hidden = YES;
    [self.view endEditing:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            if (!_pick) {
                _pick = [[UIPickerView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 50, SCREEN_HEIGHT - 216, 100, 120)];
                _pick.delegate = self;
                _pick.dataSource = self;
                _pick.showsSelectionIndicator = YES;
                [self.view addSubview:_pick];
            }
            [self tapAction];
            _pick.hidden = NO;
        } else {
            TNAddAccountContentTableViewCell *cell = (TNAddAccountContentTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
            [cell.tf becomeFirstResponder];
        }
    } else {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM '%@' WHERE money = '%@' and unit = '%@' and consume = '%@' and detailed = '%@' and time = '%@'", _str, _model.money, _model.unit, _model.consume, _model.detailed, _model.time];
        [_db executeUpdate:sql];
        [self.navigationController popViewControllerAnimated:YES];
        if (_myBlock) {
            _myBlock();
        }
    }
}

#pragma mark UIPickerViewDataSouce

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _unitArr.count;
}
#pragma mark UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 150, 30)] ;
    myView.textAlignment = NSTextAlignmentCenter;
    myView.text = _unitArr[row];
    return myView;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 100;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    cell.textLabel.text = _unitArr[row];
    _pick.hidden = YES;
}

#pragma mark - textFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _pick.hidden = YES;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
